import api from "./index";
import { initSecureKeys } from './secure';

export interface LoginData {
  username: string
  password: string
}

export interface RegisterData {
  username: string
  password: string
  company: string
  creditCode: string
  companyType: number
  industry: number
  contactPerson: string
  contactPhone: string
}

export interface UserInfo {
  id: number
  userId: String
  username: string
  companyName: string
  creditCode: string
  companyType: string
  industry: string
  contactPerson: string
  contactPhone: string
  createdAt: string
  updatedAt: string
}

// 通用响应接口
export interface ApiResponse<T> {
  code: number
  message: string
  data: T
  timestamp: number
}

// 登录响应接口
export interface LoginResponse {
  id: number
  userId: String
  username: string
  token: string
  expireTime: number
  tokenType: string
  loginTime: string
}

// 用户登录
export const login = (data: LoginData) => {
  return api.post("/user/login", data).then((res) => {
    // 保存 token 到 localStorage
    localStorage.setItem('token', res.data.token)
    localStorage.setItem('tokenType', res.data.tokenType)
    localStorage.setItem('userId', res.data.id.toString())
    localStorage.setItem('username', res.data.username)
    localStorage.setItem('user_uuid', res.data.userId)
    return res.data;
  });
};

// 用户注册
export const register = (data: RegisterData) => {
  return api.post("/user/register", data).then(async (res) => {
    if (res.data.code === 200) {
      await initSecureKeys(res.data.data.userId, data.password);
    }
    return res.data;
  });
};

// 获取用户信息
export const getUserInfo = () => {
  return api.get("/user/info").then((res) => {
    return res.data;
  });
};

// 获取好友列表
export const getFriends = (page: number, size:number) => {
  return api.get("/user/getFriends").then((res) => {
    return res.data;
  });
};

// 更新用户信息
export const updateUserInfo = (data: Partial<UserInfo>) => {
  return api.put('/user/info', data)
}

// 修改密码
export const changePassword = (data: { oldPassword: string; newPassword: string }) => {
  return api.put('/user/password', data)
}

// 更新用户设置
export const updateUserSettings = (data: { theme: string; language: string }) => {
  return api.put('/user/settings', data)
}